#ifndef BASEXML_H
#define BASEXML_H

#include <QObject>
#include <QTextCodec>
#include <QFile>
#include <QDebug>
#include <QMutex>
#include <QDomDocument>

template <class T>

class BaseXml
{

public:
    QString path() const
    {
        return m_path;
    }
    void setPath(const QString &path)
    {
        m_path = path;
    }

    static T* getInstance()
    {
        if(!m_pInstance)
        {
            QMutexLocker lock(&m_Mutex);
            if(!m_pInstance)
            {
                T *pInstance = new T();  // 修改处
                m_pInstance = pInstance;
            }
        }
        return m_pInstance;

    }

protected:

    BaseXml(){}
    virtual ~BaseXml(){}

    QString m_path;

    bool check()
    {
        QFile file(m_path);
        if (!file.open(QFile::ReadOnly | QFile::Text))
        {

#ifdef _TTY_WIN_
            QTextCodec *gbk = QTextCodec::codecForName("gb18030");
            QTextCodec::setCodecForLocale(gbk);
            qDebug()<< gbk->toUnicode(QString("Error: Cannot open xml file:" + m_path + "\n" + file.errorString()).toLocal8Bit());
#endif

#ifdef _TTY_POSIX_
           qDebug()<< "Error: Cannot open xml file:" + m_path + "\n" + file.errorString();
#endif
            return false;
        }

        QString errorStr;
        int errorLine;
        int errorColumn;

        QDomDocument doc;
        if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn))
        {
            file.close();
            qDebug()<< "Error: "+m_path+ " parse error\n" +
                       "line:" + QString::number(errorLine) + "," + "column:" + QString::number(errorColumn) + "\n" +
                       "ErrorMessage:" + errorStr;

            return false;
        }
        file.close();
        return true;
    }

    bool clearAllNode()
    {
        if(!this->check())
        {
            return false;
        }
        QFile file(m_path);
        file.open(QFile::ReadOnly | QFile::Text);
        QDomDocument doc;
        doc.setContent(&file);
        file.close();

        QDomElement root = doc.documentElement();
        QDomNode rootChild = root.firstChild();
        while (!rootChild.isNull())
        {
            root.removeChild(rootChild);
            rootChild = root.firstChild();
        }

        file.open(QFile::WriteOnly|QFile::Truncate); //先读进来，再重写，如果不用truncate就是在后面追加内容，就无效了
        QTextStream outStream(&file);
        doc.save(outStream,4); //缩进4格
        file.flush();
        file.close();
        return true;
    }

    virtual bool parser() = 0;
    virtual bool clear() = 0;

private:

    static T* m_pInstance;
    static QMutex m_Mutex;
    BaseXml(const BaseXml &);
    BaseXml &operator=(const BaseXml &);

};

template <class T>
T* BaseXml<T>::m_pInstance = NULL;
template <class T>
QMutex BaseXml<T>::m_Mutex;

#endif // BASEXML_H
